package rpc_netty.Handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.Server.RpcServer_2;
import rpc_1.object.RpcRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class RequestHandler{
    private static final Logger logger= LoggerFactory.getLogger(RequestHandler.class);

    public Object handle(RpcRequest rpcRequest, Object service) {
        Object result=null;
        try{
            result=invokeTargetService(rpcRequest,service);
            logger.info("success!");
        }catch (Exception E){
            logger.error("error when handling");
            return result;
        }
        return result;

    }

    public Object invokeTargetService(RpcRequest rpcRequest,Object service) throws InvocationTargetException, IllegalAccessException {
        Method method;
        try {
            //这里需要注意下，getMethod需要传入方法信息和方法参数类型
            method = service.getClass().getMethod(rpcRequest.getMethodName(),rpcRequest.getParamTypes());
        }catch (Exception E){
            logger.error("error when invoking!");
            return null;
        }
        return method.invoke(service,rpcRequest.getParameters());
    }


}
